#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>    //头文件
#define PORT 3490 		
float shu,k1,k2,k3;
int a;
struct occupy     //声明一个occupy的结构体   
{
char name[20];      
 float a1,a2,a3,idle,a4,cpu1;  
};
float g_cpu_used;              //定义一个全局的float类型g_cpu_used
int cpu_num;                 //定义一个全局的int类型cpu_num
void cal_occupy(struct occupy *, struct occupy *);   //声明无类型的函数cal_occupy包含两个结构体参数
int get_occupy(struct occupy *);            //声明无类型的函数get_occupy包含一个结构体参数  
int get_occupy (struct occupy *o)  //声明无类型的函数get_occupy包含一个结构体参数
{
FILE *fd;         
int n;          
char buff[1024];  
fd = fopen ("/proc/stat", "r"); 
fgets (buff, sizeof(buff), fd); 
for(n=0;n<cpu_num;n++)          
{
fgets (buff, sizeof(buff),fd);
sscanf (buff, "%s %f %f %f %f %f", &o[n].name, &o[n].a1, &o[n].a2, &o[n].a3,&o[n].idle,&o[n].a4);
}
o[1].cpu1=o[1].a1+o[1].a2+o[1].a3+o[1].idle+o[1].a4;
k1=o[1].a1;
k2=o[1].a3;
k3=o[1].cpu1;
fclose(fd); 
}

int main(int argc, char *argv[])
{
	int sockfd, numbytes;
	char buf[100];
        int leicun();
        struct occupy ocpu[10]; 
        float n,m,q1,p1,q2,p2;     
        int i;                    
        cpu_num = sysconf(_SC_NPROCESSORS_ONLN);  
	struct hostent *he;		
	struct sockaddr_in their_addr; 
	if (argc != 2) {
		fprintf(stderr,"usage: client hostname\n");
		exit(1);
	}
        if ((he=gethostbyname(argv[1])) == NULL) { 
		herror("gethostbyname");
		exit(1);
	}

	if ((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) {
		perror("socket");
		exit(1);
	}

	their_addr.sin_family = AF_INET; 
	their_addr.sin_port = htons(PORT); 		
	their_addr.sin_addr = *((struct in_addr *)he->h_addr);
	bzero(&(their_addr.sin_zero), 8); 		

	if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
		perror("connect");
		exit(1);                
	}
       while(1)
       {
  	  get_occupy (ocpu); 
  	  q1=k1; 
   	  q2=k2;                          
 	  n=k3; 
	  sleep(3);
 	  get_occupy (ocpu); 
  	  p1=k1;
	  p2=k2;     
 	  m=k3;
  	  shu= ((((p1-q1)+(p2-q2))*100)/(m-n));   
          sprintf(buf,"%f",shu);                                                             
          if (send(sockfd, buf, sizeof(buf), 0) == -1) perror("send");
          leicun();
          sprintf(buf,"%d",a);  
          if (send(sockfd, buf, sizeof(buf), 0) == -1) perror("send");
       }
        close(sockfd); 	
        return 0;
}

int leicun()
{
	FILE *fp;
	char mem[10];
	double meminfo[2];
	float mem_rate;
	char text[1024];
	

	fp=fopen("/proc/meminfo","r");
	int index=0;
	
	while(!feof(fp))
	{
		if(index<2)
		{		
			fgets(text,1024,fp);	
	
			sscanf(text,"%s %lf\n",mem,&meminfo[index]);
			
			index++;
		}
		else break;
		
	}
	fclose(fp);
	mem_rate=(1-meminfo[1]/meminfo[0])*100;
	a=mem_rate;
	sleep(1);
	return (a);
}

